package com.clever.mall.service.impl;

import com.clever.mall.commons.dto.RefundDto;
import com.clever.mall.commons.exception.ServiceException;
import com.clever.mall.commons.result.BaseResult;
import com.clever.mall.entity.Order;
import com.clever.mall.entity.Refund;
import com.clever.mall.entity.TradingRecord;
import com.clever.mall.entity.User;
import com.clever.mall.mapper.OrderMapper;
import com.clever.mall.mapper.RefundMapper;
import com.clever.mall.mapper.TradingRecordMapper;
import com.clever.mall.mapper.UserMapper;
import com.clever.mall.service.OrderService;
import com.clever.mall.service.RefundService;
import com.clever.mall.utils.MyBeanUtils;
import com.clever.mall.utils.StatusCode;
import com.clever.mall.vo.RefundVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * @program: project-item
 * @author: hzx
 * @since: JDK 1.8
 * @create: 2020-11-12 10:14
 **/
@Service
public class RefundServiceImpl implements RefundService {
    //退款
    @Resource
    private RefundMapper mapper;

    //订单
    @Resource
    private OrderMapper oMapper;

    //用户
    @Resource
    private UserMapper uMapper;

    //订单业务
    @Resource
    private OrderService orderService;

    //交易记录
    @Resource
    private TradingRecordMapper tradingRecordMapper;

    /**
     * 添加退款信息
     * @param refundDto
     * @return
     */
    @Override
    @Transactional
    public int insertRefund(RefundDto refundDto) {
        //数据验证
        if (refundDto == null) {
            throw new ServiceException(StatusCode.ORDER_INSERT_NULL);
        }
        //查询退款数据
        Refund refundSelect = new Refund();
        refundSelect.setOrderId(refundDto.getOrderId());
        Refund nowRefund = mapper.selectRefund(refundSelect);
        //获取订单数据
        Order order = oMapper.selectOrderByOrderId(refundDto.getOrderId());
        //订单状态
        if (order.getStatus() < 1) {
            throw new ServiceException(StatusCode.ORDER_UNPAID);
        }
        //订单退款状态
        if ((order.getRefundStatus() > 0 && order.getRefundStatus() != 2) || nowRefund != null) {
            throw new ServiceException(StatusCode.REFUND_FOR_ERROR);
        }

        //复制数据
        Refund refund = new Refund();
        MyBeanUtils.copyProperties(refundDto,refund);

        //添加退款数据
        int affect = mapper.insertRefund(refund);
        if (affect != 1) {
            throw new ServiceException(StatusCode.ADD_DATABASE_DATA_ERROR);
        }
        //修改订单退款状态
        if (oMapper.updateOrderRefundStatus(refund.getOrderId(), 1) != 1) {
            throw new ServiceException(StatusCode.ADD_DATABASE_DATA_ERROR);
        }

        return affect;
    }

    /**
     * 查询所有退款信息
     * @param uid
     * @return
     */
    @Override
    public List<RefundVo> selectRefundAll(int uid) {
        if (uid < 1) {
            throw new ServiceException(StatusCode.DATA_FORMAT_ERROR);
        }
        //查询
        List<Refund> refunds = mapper.selectRefundAll(uid);
        if (refunds == null || refunds.size() == 0) {
            throw new ServiceException(StatusCode.NO_DATA_ERROR);
        }
        //复制数据
        List<RefundVo> refundVos = MyBeanUtils.copyListProperties(refunds, RefundVo::new);
        return refundVos;
    }

    /**
     * 通过id查询
     * @param rid
     * @return
     */
    @Override
    public RefundVo selectRefundById(int rid) {
        if (rid < 1) {
            throw new ServiceException(StatusCode.DATA_FORMAT_ERROR);
        }
        //查询
        Refund refund = mapper.selectRefundById(rid);
        if (refund == null) {
            throw new ServiceException(StatusCode.NO_DATA_ERROR);
        }
        //复制数据
        RefundVo refundVo = new RefundVo();
        MyBeanUtils.copyProperties(refund,refundVo);

        return refundVo;
    }

    /**
     * 修改退款状态（必要数据：订单id(orderId)、退款状态(refundStatus)）
     * @param refundDto
     * @return
     */
    @Override
    @Transactional
    public int updateRefundStatus(RefundDto refundDto) {
        //数据验证
        if (refundDto == null) {
            throw new ServiceException(StatusCode.ORDER_INSERT_NULL);
        }
        if (refundDto.getRefundStatus() == null) {
            throw new ServiceException(StatusCode.DATA_FORMAT_ERROR);
        }
        //获取退款记录
        Refund refund = mapper.selectRefundByOrderId(refundDto.getOrderId());
        //判断退款记录是否存在
        if (refund == null) {
            throw new ServiceException(StatusCode.REFUND_DATA_ERROR);
        }
        //格式验证
        if (refundDto.getRefundStatus() < 2 || refundDto.getRefundStatus() > orderService.REFUND_STATUS_COMPLETE
                || refundDto.getRefundStatus() <= refund.getRefundStatus()) {
            throw new ServiceException(StatusCode.DATA_FORMAT_ERROR);
        }

        //复制数据
        Refund refundAdd = new Refund();
        //MyBeanUtils.copyProperties(refundDto,refundAdd);
        refundAdd.setRefundId(refund.getRefundId());
        refundAdd.setRefundStatus(refundDto.getRefundStatus());
        if (refundDto.getRefundStatus() == orderService.REFUND_STATUS_COMPLETE) {
            refundAdd.setOrderStatus(orderService.STATUS_COMPLETE);
        }
        //调用数据库进行修改
        int affect = mapper.updateRefundStatus(refundAdd);
        if (affect != 1) {
            throw new ServiceException(StatusCode.UPDATE_DATA_ERROR);
        }

        //修改订单退款状态
        orderService.updateOrderRefundStatus(refund.getOrderId(),refundAdd.getRefundStatus());

        //如要修改的状态‘为完成退款’，则将钱退回买家账户
        if (refundAdd.getRefundStatus() == orderService.REFUND_STATUS_COMPLETE) {
            //退款
            refundStart(refund);
        }

        return affect;
    }

    //退款
    private void refundStart(Refund refund) {
        User user = new User();
        //退款金额
        BigDecimal totalPrice = refund.getPrice();
        //用户
        user.setUserId(refund.getUserId());
        user = uMapper.selectUserByUser(user);
        //用户余额加商品价格
        BigDecimal balance = user.getBalance().add(totalPrice);
        //修改余额
        user.setBalance(balance);
        if (uMapper.updateUser(user) < 1) {
            throw new ServiceException(StatusCode.ORDER_PAY_ERROR);
        }

        //添加交易记录
        TradingRecord tradingRecord = new TradingRecord();
        tradingRecord.setUserId(refund.getUserId());
        tradingRecord.setType(4);
        tradingRecord.setMoney(totalPrice);
        if (tradingRecordMapper.insertTradingRecord(tradingRecord) != 1) {
            throw new ServiceException(StatusCode.TRANSACTION_RECORDS_ERROR);
        }
    }
}
